package IBBB.network.sendmessage;

import server.Word;
import IBBB.model.WordsMessage;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.LinkedHashMap;
import java.util.Map;

public class send_ask_for_word extends send_String {
    public WordsMessage getWordsMessage() {
        return wordsMessage;
    }

    private Map<String, String> map = new LinkedHashMap<>();
    {
        map.put("四级真题词汇","cet4");
        map.put("六级真题词汇","cet6" );
        map.put("考研英语基础","kaoyan" );
        map.put("托福词汇","toefl");
        map.put("雅思词汇", "ielts");
    }
    private WordsMessage wordsMessage;
    public send_ask_for_word(String server, String username, String dictionaryname, String type, Integer amount ) {
        super(server);
        target_message="queryWords#"+username+"#"+map.get(dictionaryname)+"#"+type+"#"+amount;
    }


    @Override
    public Void call() {
        Socket client = new Socket();
        try {
            client.connect(message_socket, 3000);
        } catch (Exception e) {
            updateMessage("timeout");
            return null;
        }

        try (ObjectOutputStream writer = new ObjectOutputStream(client.getOutputStream())) {
            try (ObjectInputStream reader = new ObjectInputStream(client.getInputStream())) {
                writer.writeObject(target_message);
                Map<String, Word> words = (Map<String, Word>) reader.readObject();
                client.close();
                wordsMessage = new WordsMessage(words);
                updateMessage("success");
            }
        } catch (Exception e) {
            updateMessage("wrong");
        }
        return null;
    }
}
